package com.wavehi.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author WaveHi
 * @Date 28/9/2021 上午 10:04
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description
 */
@WebFilter(
    urlPatterns = "*.jsp"
)
public class UserIndexFilter extends BaseFilter{
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("I am index filter!");
        //获取请求的资源路径
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;
        String requestURI = req.getRequestURI();
        //检验资源路径
        boolean isCorrectResources = !"login.jsp".equals(requestURI.substring(requestURI.lastIndexOf("/") + 1));
        //检验登录信息
        boolean exist = req.getSession().getAttribute("user") != null;
        if(isCorrectResources && !exist) {
            resp.sendRedirect("/login.jsp");
            return;
        }
        //让请求继续传递下去
        filterChain.doFilter(req, resp);
    }
}
